﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using DBUtil;

namespace NewLIMS_QueueService
{
    public class QueueService : ServiceBase
    {
        public static Timer timer = new Timer();
        public static double interval = (1000 * 60) * 5; // 5 分钟 间隔执行


        /// <summary>
        /// 如果 间隔执行设定修改，则在下次执行更新间隔时间段
        /// </summary>
        private void RefashInterval()
        {
            ConfigurationManager.RefreshSection("connectionStrings");
            ConfigurationManager.RefreshSection("appSettings");
            interval = Utils.ConvertTo<double>(ConfigurationManager.AppSettings["Interval"], 3);
            timer.Interval = interval * (1000 * 60);
        }

        protected override void OnStart(string[] args)
        {
            RefashInterval();
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
            LogUtils.LogInfo("新系统 二维码html生成服务开始", Developer.MJ);
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            RefashInterval();
            try
            {
                Execute();
            }
            catch (Exception ex)
            {
                LogUtils.LogError("新系统 二维码html生成服务异常", Developer.MJ, ex, ex.InnerException);
            }
        }

        protected override void OnStop()
        {
            LogUtils.LogInfo("新系统 二维码html生成服务停止", Developer.MJ);
        }

        protected override void OnShutdown()
        {
            LogUtils.LogInfo("新系统 二维码html生成服务关闭", Developer.MJ);
        }

        static object locker = new object();
        public void Execute()
        {
            lock (locker)
            {
                //每次取10条
                string sel_sql = "Select Replace(SELECTNO,'New_') as SELECTNO,Url,Rownum From Lims_SendReportQueue a Where Rownum<=10 And  a.state = 0 Order By ADDTIME Asc";
                DBSession db = new DBSession(DataBaseType.OracleManaged);              
                var dictQueue = db.QueryTable(sel_sql, 300).GetDict<string, string>("SELECTNO", "Url");
                if (dictQueue.Count > 0)
                {
                    Queue<string> QueSltNo = new Queue<string>(dictQueue.Keys);

                    while (QueSltNo.Count > 0)
                    {
                        string code = QueSltNo.Dequeue();
                        string url = dictQueue[code];
                        sel_sql = "Select a.code 报告编号,a.委托单位,a.委托日期,a.来样日期,a.样品名称,a.规格型号 As 型号规格,a.生产单位 ,a.检验依据,a.检验项目 As 检测项目,a.Result As 检测结论,a.REPOTDATE As 签发日期,a.检验方 As 检验单位 From Vm_WtBusinessEnregisterInfo a Where a.Code ='{0}' ";
                        sel_sql = string.Format(sel_sql, code);
                        DataTable data = db.QueryTable(sel_sql, 300);

                        string html = GetQrCodeContent();
                        StringBuilder sb = new StringBuilder();
                        foreach (DataColumn dc in data.Columns)
                        {
                            string columnName = dc.ColumnName;
                            string value = data.Rows[0][columnName].ToString();

                            if (columnName == "检验依据" || columnName == "检测结论" || columnName == "检测项目")
                            {
                                if (!string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(value.Trim()))
                                {
                                    value = ReplaceSpecialChar(value);
                                }
                            }
                            sb.AppendLine("<tr><td class=\"td-header\">" + columnName + "</td><td  class=\"td-content\">" + value + "</td></tr>");
                        }
                        string tr_html = sb.ToString() + GetCommonInfo();
                        html = html.Replace("{content}", tr_html);

                        //更新状态及保存html内容
                        Hashtable ht = new Hashtable();
                        ht.Add("State", 1);
                        ht.Add("QueueTime", DateTime.Now);
                        if (string.IsNullOrWhiteSpace(url))
                        {
                            ht.Add("Url", GetQRPath(code));
                        }
                        ht.Add("HtmlContent", html);
                        ht.Add("SelectNo", "New_" + code);
                        int res = db.Update(ht, "LIMS_SendReportQueue", "SelectNo");
                        LogUtils.LogInfo("新系统 二维码html生成服务 执行更新", Developer.MJ, code);
                    }
                }
                else//没有则休息
                {
                    LogUtils.LogInfo("新系统 二维码html生成服务 Sleep", Developer.MJ, "休眠：3000ms");
                    System.Threading.Thread.Sleep(3000);
                }
            }
        }

        /// <summary>
        /// 获取二维码html的路径地址
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetQRPath(string code)
        {
            string qr_url = string.Empty;
            string[] splitChars = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

            //报告编号中如果有 0-9 的字符串,进行split
            string[] strs = code.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);

            //报告编号url 二维码地址生成规则，New 表示新系统
            //如：FH2016NG0005 ，生成后  /New/FHNG/RkgyMDE2TkcwMDA1.html
            if (strs != null && strs.Length > 0)
            {
                qr_url = "/" + "New/" + string.Join("", strs) + "/" + Utils.ToBase64(code) + ".html";
            }
            else
            {
                qr_url = "/" + "New/" + Utils.ToBase64(code) + ".html";
            }
            return qr_url;
        } 

        /// <summary>
        /// 将报告中的特殊字符替换为图片地址
        /// </summary>
        /// <returns></returns>
        public static string ReplaceSpecialChar(string val)
        {
            if (string.IsNullOrEmpty(val))
            {
                return string.Empty;
            }
            DBSession db = new DBSession(DataBaseType.OracleManaged);
            string sql = "SELECT * FROM LIMS_SpecialChar WHERE Str IN " + Utils.GetInSqlChar(val) + "";
            DataTable dt_special = db.QueryTable(sql, 300);
            if (dt_special != null && dt_special.Rows.Count > 0)
            {
                foreach (DataRow dr in dt_special.Rows)
                {
                    string special_str = dr["Str"].ToString();
                    string imgUrl = dr["ImgUrl"] != null ? dr["ImgUrl"].ToString() : string.Empty;
                    if (!string.IsNullOrEmpty(imgUrl))
                    {
                        string img = "<img src=\"" + imgUrl + "\"/>";
                        val = val.Replace(special_str, img);
                    }
                }
            }
            return val;
        }

        /// <summary>
        /// 获取二维码扫描跳转的url hml页面模板
        /// </summary>
        /// <returns></returns>
        public static string GetQrCodeContent()
        {
            string htmlfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Template\\QrCodeContent.html");
            if (File.Exists(htmlfile))
            {
                return File.ReadAllText(htmlfile, Encoding.UTF8);
            }
            return string.Empty;
        }

        /// <summary>
        /// 二维码html内容的尾部公共信息
        /// </summary>
        /// <returns></returns>
        public static string GetCommonInfo()
        {
            string qr_website = ConfigurationManager.AppSettings["QR_Common_WebSite"];
            string qr_phone = ConfigurationManager.AppSettings["QR_Common_Phone"];
            string qr_fax = ConfigurationManager.AppSettings["QR_Common_Fax"];
            string qr_address = ConfigurationManager.AppSettings["QR_Common_Address"];

            StringBuilder sb = new StringBuilder();
            if (!string.IsNullOrEmpty(qr_website))
            {
                qr_website = string.Format("<a href='{0}'>{0}</a>", qr_website.Trim());
                sb.AppendLine("<tr><td class=\"td-header\">" + "网址" + "</td><td  class=\"td-content\">" + qr_website + "</td></tr>");
            }
            if (!string.IsNullOrEmpty(qr_phone))
            {
                sb.AppendLine("<tr><td class=\"td-header\">" + "客服电话" + "</td><td  class=\"td-content\">" + qr_phone.Trim() + "</td></tr>");
            }
            if (!string.IsNullOrEmpty(qr_fax))
            {
                sb.AppendLine("<tr><td class=\"td-header\">" + "传真" + "</td><td  class=\"td-content\">" + qr_fax.Trim() + "</td></tr>");
            }
            if (!string.IsNullOrEmpty(qr_address))
            {
                sb.AppendLine("<tr><td class=\"td-header\">" + "地址" + "</td><td  class=\"td-content\">" + qr_address.Trim() + "</td></tr>");
            }
            return sb.ToString();
        }
    }
}
